<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 11/14/18
 * Time: 8:23 PM
 */

namespace caroltc\jenkinsapp\util;


class Helper
{
    /**
     * 加密函数
     * @param $txt
     * @param string $key
     * @return string
     */
    public static function lock($txt,$key = '')
    {
        $key .= 'xxOl_l.S1O19';
        if (empty(trim($txt))) {
            return $txt;
        }
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $ch = $chars[rand(0,64)];
        $mdKey = substr(md5($key.$ch),rand(0,10), 4);
        $txtEncode = base64_encode($mdKey . $txt);
        $checkKey1 = substr(md5($txt.$mdKey),4,3);
        $checkKey2 = substr(md5($txtEncode . $key),8,3);
        $randomKey = substr(md5($ch),2,4);
        return $checkKey1 . $randomKey . $checkKey2  . $txtEncode;
    }

    /**
     * 解密函数
     * @param $txt
     * @param string $key
     * @return bool|string
     */
    public static function unlock($txt,$key = '')
    {
        $key .= 'xxOl_l.S1O19';
        if (empty(trim($txt))) {
            return $txt;
        }
        if (strlen($txt) < 14) {
            return $txt;
        }

        $checkKey1 = substr($txt, 0,3);
        $checkKey2 = substr($txt, 7,3);
        $txtEncode = substr($txt, 10);
        if ($checkKey2 !== substr(md5($txtEncode . $key),8,3)) {
            return $txt;
        }
        $txtmdKey = base64_decode($txtEncode);
        if ($txtmdKey === false || empty($txtmdKey)) {
            return $txt;
        }
        $mdKey = substr($txtmdKey, 0,4);
        $txtStr = substr($txtmdKey, 4);
        if ($checkKey1 !== substr(md5($txtStr . $mdKey),4,3)) {
            return $txt;
        }

        return $txtStr;
    }

    /**
     * 毫秒级时间戳
     * @return float
     */
    public static function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }
}